import {
    changeData,
    changeMeta,
    checkBillId,
    COMMON,
    getBillid, getBilltype,
    getCheckedRows,
    getTableTmp, getUrlParam, setFormState, toastMsg,
    updateButtonStatus
} from "../main/util";
import {saveValidate} from "../../../public/functions/unit";
import {
    toast,
    promptBox,
    print,
    output,
    cacheTools
} from 'nc-lightapp-front';
import deepCopy from 'src/hrpub/common/utils/deep-copy';
import do_print from 'src/hrpub/common/utils/print';
import Export from 'src/hrpub/common/utils/exportHtml';

export default class ButtonAction {
    constructor(comp) {
        this.comp = comp;
        this.dispatch = this.comp.props.dispatch;
    }

    // 第一次进页面的按钮状态
    initPageButton = () => {
        const {props} = this.comp;
        const {
            button
        } = props;

        button.setButtonDisabled({
            add: false,
            refresh: false
        });
    };

    //指派弹窗确定事件
    getResult = (compositepostdata) => {
        const {props} = this.comp
        const {transfer} = props
        let billids = null
        if (transfer.page === COMMON.pageMain) {
            billids = getCheckedRows(props, 'pk_hi_stapply');
        } else if (transfer.page === COMMON.pageDetail) {
            billids = transfer.billid;
        }
        if (!checkBillId(toast, billids, transfer)) return;
        this.commit({billids, compositepostdata})
    };

    //指派弹窗取消事件
    turnOff = () => {
        const {props} = this.comp;
        const {dispatch} = props;
        dispatch({
            type: 'transfer/update',
            payload: {
                compositedata: null,
                compositedisplay: false,
            }
        })
    };

    // 按钮点击回调
    headerClick = (props, btnCode, area, record) => {
        const {action, props: {transfer}} = this.comp;
        // 查询
        if (btnCode === 'search') {
            this.showSearchModal();
        }
        // 刷新
        else if (btnCode === 'refresh') {
            this.pubSub.publish('getMainTableData', {
                callback: () => {
                    toast({
                        color: 'success',
                        content: transfer.language['gx6008-000120'] // 刷新成功
                    });
                }
            });
        }
        // 刷新
        else if (btnCode === 'refresh_d') {
            this.comp.action.detailAct.queryDetailData({
                callback: () => {
                    toast({
                        color: 'success',
                        content: transfer.language['gx6008-000120'] // 刷新成功
                    });
                }
            });
        }
        // 新增
        else if (btnCode === 'add' || btnCode === 'add_d') {
            this.add(btnCode);
        }
        // 删除
        else if (btnCode === 'del' || btnCode === 'del_d') {
            let billids;
            if (transfer.page === COMMON.pageMain) {
                billids = getCheckedRows(props, 'pk_hi_stapply');
            } else if (transfer.page === COMMON.pageDetail) {
                billids = transfer.billid;
            }
            if (!checkBillId(toast, billids, transfer)) return;
            promptBox({
                color: "warning",
                title: transfer.language['gx6008-000018'], /* 国际化处理： 提示*/
                content: transfer.language['gx6008-000019'], /* 国际化处理： */
                beSureBtnClick: () => {
                    this.delete({billids});
                }
            });
        }
        // 提交
        else if (btnCode === 'commit') {
            let billids;
            billids = getCheckedRows(props, 'pk_hi_stapply');
            if (!checkBillId(toast, billids, transfer)) return;
            this.commit({billids})
        }
        // 提交 详情页
        else if (btnCode === 'commit_d') {
            this.commit()
        }
        // 收回
        else if (btnCode === 'recover') {
            let billids;
            billids = getCheckedRows(props, 'pk_hi_stapply');
            if (!checkBillId(toast, billids, transfer)) return;
            this.recover({billids})
        }
        // 收回 详情页
        else if (btnCode === 'recover_d') {
            this.recover()
        }
        // 编制情况
        else if (btnCode === 'organization' || btnCode === 'organization_d') {
            let billids;
            if (transfer.page === COMMON.pageMain) {
                billids = getCheckedRows(props, 'pk_hi_stapply');
            } else if (transfer.page === COMMON.pageDetail) {
                billids = transfer.billid;
            }
            if (!checkBillId(toast, billids, transfer)) return;
            this.organization(billids)
        }
        // 合同查看
        else if (btnCode === 'check_contract' || btnCode === 'checkContract_d') {
            let billids;
            if (transfer.page === COMMON.pageMain) {
                billids = getCheckedRows(props, 'pk_hi_stapply');
            } else if (transfer.page === COMMON.pageDetail) {
                billids = transfer.billid;
            }
            if (!checkBillId(toast, billids, transfer)) return;
            this.viewContract(billids)
        }
        // 发送通知
        else if (btnCode === 'sendMsg') {
            let billids;
            billids = getCheckedRows(props, 'pk_hi_stapply');
            if (!checkBillId(toast, billids, transfer)) return;
            this.sendMsg({billids})
        }
        //  批量新增
        else if (btnCode === 'batchAdd') {
            action.batAddAct.openBatchModal();
        }
        // 打印
        else if (btnCode === 'print') {
            this.htmlPrint()
        }
        // 打印
        else if (btnCode === 'print_d') {
            this.templatePrint()
        }
        // 输出
        else if (btnCode === 'out') {
            this.htmlOut()
        }
        // 输出
        else if (btnCode === 'out_d') {
            this.templateOut()
        }
        // 编辑
        else if (btnCode === 'edit') {
            let billid = record.values.pk_hi_stapply.value;
            this.edit(billid);
        }
        // 编辑
        else if (btnCode === 'edit_d') {
            this.edit();
        }
        // 查看审批意见 （列表页）
        else if (btnCode === 'checkApprOpini') {
            let billid = getBillid(record);
            let billtype = getBilltype(record);
            this.checkApprOpini(billid, billtype);
        }
        // 查看审批意见 (详情页）
        else if (btnCode === 'checkOpini') {
            this.checkApprOpini();
        }
        // 复制
        else if (btnCode === 'copy') {
            let billid = record.values.pk_hi_stapply.value;
            this.copy(billid);
        }
        // 复制
        else if (btnCode === 'copy_d') {
            this.copy();
        }
        // 附件管理
        else if (btnCode === 'file_d') {
            const {props} = this.comp;
            const {dispatch} = props;

            dispatch({
                type: 'transfer/update',
                payload: {
                    fileManagerBillId: transfer.billid,
                    fileManagerModalVisible: true
                }
            });
        }
        // 保存
        else if (btnCode === 'save') {
            this.save();
        }
        // 取消
        else if (btnCode === 'cancel') {
            this.cancel();
        }
        else if(btnCode === 'psncard_d' || btnCode === 'psncard'){
            this.linkSearch()
        }
        // 执行
        else if (btnCode === 'execute'||btnCode ==="execute_d") {
            let billids;
            if (transfer.page === COMMON.pageMain) {
                billids = getCheckedRows(props, 'pk_hi_stapply');
            } else if (transfer.page === COMMON.pageDetail) {
                billids = transfer.billid;
            }
            if (!checkBillId(toast, billids, transfer)) return;
            this.execute(billids);
        }

    };

    linkSearch = async() =>{
		const {action,props} = this.comp
		const {form,transfer,editTable} = props
    	if(transfer.page === 'main') {
            let rows = editTable.getCheckedRows('list');
			transfer.nodeRefs.wpsview.openView(rows);

		} else{
            let formData = form.getAllFormValue('card').rows;
			transfer.nodeRefs.wpsview.openView(formData);
		}
	}
    //新增
    add = async (btnCode) => {
        const {props} = this.comp;
        const {transfer} = props;
        let postData = {
            pk_org: transfer.hrorgobj.refpk,
            transMode: transfer.stapplyMode,
            transType: transfer.trnsType.refpk,
        };
        let res = await this.dispatch({
            type: 'transfer/add',
            payload: {
                postData
            }
        });
        if (!res) return;
        this.dispatch({
            type: 'transfer/update',
            payload: {
                billid:null
            }
        });
        if (this.comp.action.detailAct) {
            await this.comp.action.detailAct.setDetailData(res.data, COMMON.formId, null, btnCode);
        }
        await this.editForm(true);
        if (btnCode === 'add_d') {
            setFormState(props, res);
        }
    };

    /**
     * 编辑表单
     * @param isEdit
     */
    editForm = async (isEdit) => {
        const {props} = this.comp;
        const {dispatch} = props;
        props.form.setFormStatus(COMMON.formId, isEdit ? 'edit' : 'browse');
        await dispatch({
            type: 'transfer/update',
            payload: {
                page: COMMON.pageDetail,
                isEditDetail: isEdit
            }
        });
    };

    //编辑
    edit = async (billid) => {
        let {props} = this.comp;
        let {transfer} = props;
        !billid && (billid = transfer.billid);
        let isapprove = getUrlParam(props).fromScene;
        if (!isapprove && getUrlParam(props).status) {
            isapprove = 'approvesce';
        }
        let postData = {
            billid,
            isapprove,
            pk_org: transfer.hrorgobj.refpk,
        };
        try {
            let res = await this.dispatch({
                type: 'transfer/editAction',
                payload: {
                    postData
                }
            });
            if (!res.success) return;
            // 显示详情页
            await this.comp.action.detailAct.setDetailData(res.data, COMMON.formId);
            await this.editForm(true);
            if (transfer.page === COMMON.pageDetail) {
                setFormState(props, res);
            }
        } catch (e) {
            console.error(e);
        }
    };

    //查看审批意见
    checkApprOpini = async (billid, billtype) => {
        let {props} = this.comp;
        let {transfer} = props;
        !billid && (billid = transfer.billid);
        !billtype && (billtype = transfer.billtype);
        this.dispatch({
            type: 'transfer/update',
            payload: {
                billid,
                billtype,
                approveDetail: true
            }
        });
    };

    //复制
    copy = async (billid) => {
        let {props} = this.comp;
        let {transfer} = props;
        !billid && (billid = transfer.billid);
        let postData = {
            billid,
            page_code: COMMON.appConfig.pagecode,
            area_code: "card",
            pk_org: transfer.hrorgobj.refpk,
        };
        try {
            let res = await this.dispatch({
                type: 'transfer/copyAction',
                payload: {
                    postData
                }
            });
            if (!res.success) return;
            // 显示详情页  填写数据
            this.comp.action.detailAct.setDetailData(res.data, COMMON.formId);
            this.editForm(true)
        } catch (e) {
            console.error(e)
        }
    };

    //保存
    save = async () => {
        let {props} = this.comp;
        let {form,transfer} = props;
        let formData = form.getAllFormValue(COMMON.formId);
        // if (!form.isCheckNow(COMMON.formId)) return;
        let values = formData.rows[0].values;
        let postData = {
            formData,
            pk_org: values.pk_org.value,
            transMode: values.stapply_mode.value,
            page_code: COMMON.appConfig.pagecode
        };
        let check = await this.beforeSave(postData);
        if (!check) return;
        let bodys_code = ['psninfo','oldinfo','newinfo','stapply_mng_org','contract_mng_org','execinfo','table_end_info','audit_info'];
        saveValidate(props, transfer.templateIdObj.template, COMMON.formId, bodys_code, 'extcard').then(async ()=>{
            try {
                let res = await this.dispatch({
                    type: 'transfer/saveAction',
                    payload: {
                        postData
                    }
                });
                if (!res) return;
                await this.comp.action.detailAct.setDetailData(res.data, COMMON.formId);
                toast({
                    color: 'success',
                    content: this.comp.props.transfer.language['gx6008-000030'] // 保存成功
                });
                this.back();
            } catch (e) {
                console.error(e)
            }
        })

    };

    beforeSave = async (postData) => {
        try {
            let res = await this.dispatch({
                type: 'transfer/saveCheckAction',
                payload: {
                    postData
                }
            });
            toastMsg(res);
            return res.success
        } catch (e) {
            return false
        }

    };

    //取消
    cancel = async () => {
        let {props} = this.comp;
        let {form, transfer} = props;
        let formData = form.getAllFormValue(COMMON.formId);
        let values = formData.rows[0].values;
        let postData = {
            formData,
            pk_org: values.pk_org.value
        };

        // 如果是修改 则直接返回
        if (transfer.billid) {
            this.back();
            return;
        }
        try {
            let res = await this.dispatch({
                type: 'transfer/cancelAction',
                payload: {
                    postData
                }
            });
            if (!res.success) return;

            updateButtonStatus(props, null);
            this.back();
        } catch (e) {

        }
    };

    //删除
    delete = async ({billids} = {}) => {

        let {transfer} = this.comp.props;
        !billids && transfer.billid && (billids = [transfer.billid]);
        let postData = {
            billids,
            pk_org: transfer.hrorgobj.refpk
        };
        try {
            let res = await this.dispatch({
                type: 'transfer/delAction',
                payload: {
                    postData
                }
            });
            if (!res.success) return;
            toast({
                color: 'success',
                content: transfer.language['gx6008-000017'] // 删除成功
            });
            this.back();
        } catch (e) {

        }
    };

    commit = async ({billids, effectDate, pk_org, compositepostdata = null} = {}) => {
        let {props} = this.comp;
        let {transfer, dispatch} = props;
        !billids && transfer.billid && (billids = [transfer.billid]);
        !pk_org && (pk_org = transfer.hrorgobj.refpk);
        if (!checkBillId(toast, billids, transfer)) return;
        let postData = {
            billids,
            pk_org
        };

        if (compositepostdata && compositepostdata.content) {
            postData = Object.assign({}, postData, {content: compositepostdata})
        }

        try {
            let res = await this.dispatch({
                type: 'transfer/commitAction',
                payload: {
                    postData
                }
            });
            if (!res.success) return;
            if (res.data.content) {
                dispatch({
                    type: 'transfer/update',
                    payload: {
                        compositedata: res.data.content,
                        compositedisplay: true
                    }
                });
                return
            }

            if (transfer.page === COMMON.pageMain) {
                this.pubSub.publish('getMainTableData');
            } else if (transfer.page === COMMON.pageDetail) {
                this.comp.action.detailAct.queryDetailData();
            }
            if (this.checkErrorMsg(res)) {
                toast({
                    color: 'success',
                    content: transfer.language['gx6008-000047'] // 提交成功
                });
            }
            dispatch({
                type: 'transfer/update',
                payload: {
                    compositedata: null,
                    compositedisplay: false,
                    compositepostdata: null
                }
            });
        } catch (e) {
            console.log(e)
        }
    };

    execute = async (billids) => {
        let {props} = this.comp;
        let {transfer} = props;
        let postData = {
            billids,
            pk_org: transfer.hrorgobj.refpk
        };
        let excuteVisible = await this.beforeExecute(postData);
        if (!excuteVisible) return;
        this.dispatch({
            type: 'transfer/update',
            payload: {
                excuteVisible
            }
        });
    };
    beforeExecute = async (postData) => {
        let {props} = this.comp;
        let {transfer} = props;
        try {
            let res = await this.dispatch({
                type: 'transfer/beforeExcuteAction',
                payload: {
                    postData
                }
            });
            let flag;
            await toastMsg(res, transfer, () => {
                flag = true;
            }, () => {
                flag = false;
            });
            if(typeof flag === 'boolean'){
                return res.success && flag
            }
            return res.success
        } catch (e) {
            return false
        }

    };

    // 收回
    recover = async ({billids, effectDate, pk_org} = {}) => {
        let {props: {transfer}} = this.comp;
        !billids && transfer.billid && (billids = [transfer.billid]);
        !pk_org && (pk_org = transfer.hrorgobj.refpk);
        if (!checkBillId(toast, billids, transfer)) return;
        let postData = {
            billids,
            pk_org
        };
        try {
            let res = await this.dispatch({
                type: 'transfer/callbackAction',
                payload: {
                    postData
                }
            });
            if (!res.success) return;
            if (this.checkErrorMsg(res)) {
                toast({
                    color: 'success',
                    content: transfer.language['gx6008-000048'] // 提交成功
                });
            }
            if (transfer.page === COMMON.pageMain) {
                this.pubSub.publish('getMainTableData');
            } else if (transfer.page === COMMON.pageDetail) {
                this.comp.action.detailAct.queryDetailData();
            }
        } catch (e) {

        }
    };

    // 编织情况
    organization = async (billids) => {
        let {props: {transfer}} = this.comp;
        !billids && transfer.billid && (billids = [transfer.billid]);
        let flag = checkBillId(toast, billids, transfer);
        if (!flag) return;
        this.pubSub.publish('showOrganization');
    };

    // 合同查看
    viewContract = (billids) => {
        let {props: {transfer}} = this.comp;
        !billids && transfer.billid && (billids = [transfer.billid]);
        if (!checkBillId(toast, billids, transfer)) return;
        this.pubSub.publish('showViewContract');
    };

    // 发送通知
    sendMsg = async ({billids, pk_org} = {}) => {
        let {props: {transfer}} = this.comp;
        !billids && transfer.billid && (billids = [transfer.billid]);
        !pk_org && (pk_org = transfer.hrorgobj.refpk);
        if (!checkBillId(toast, billids, transfer)) return;
        let postData = {
            billids,
            pk_org
        };
        try {
            let res = await this.dispatch({
                type: 'transfer/sendMsgAction',
                payload: {
                    postData
                }
            });
            if (!res) return;
            if (res.success && res.data) {
                toast({
                    color: 'success',
                    content: res.data // 提交成功
                });
            }
        } catch (e) {

        }
    };

    // 检查返回值里是否有 errorMsg
    checkErrorMsg = (res) => {
        if (res.data && (res.data.errorMsg || res.data.message)) {
            toast({
                color: 'danger',
                content: res.data.errorMsg || res.data.message
            });
            return false
        }

        return true;
    };

    /**
     * 返回
     */
    back = () => {
        let {props} = this.comp;
        let {transfer} = props;
        let isEditDetail = transfer.isEditDetail;
        let curpage = isEditDetail ? COMMON.pageDetail : COMMON.pageMain;
        let payload = {
            page: curpage,
            isEditDetail: false
        };
        if (!isEditDetail) {
            payload.billid = null
        }
        this.dispatch({
            type: 'transfer/update',
            payload: {
                ...payload
            }
        });

        if (curpage === COMMON.pageMain) {
            if(transfer.widget){
                this.pubSub.publish('getWidgetTableData');
            }else{
                this.pubSub.publish('getMainTableData');
            }
        } else if (curpage === COMMON.pageDetail) {
            let billid = transfer.billid;
            // 如果没有billid则表示是新增 设置billid 返回后详情页显示第一个单据的数据
            if (!billid) {
                let allpks = cacheTools.get('allpks');
                if (allpks && Array.isArray(allpks)) {
                    billid = allpks[0];
                }
            }
            // 有billid 请求数据 ； 否则 this.editForm 函数中清空数据
            if (billid) {
                this.comp.action.detailAct.queryDetailData({billid})
            } else {
                props.form.EmptyAllFormValue(COMMON.formId);
            }
        }
        props.form.setFormStatus(COMMON.formId, 'browse');
    };

    // 展示查询弹窗
    showSearchModal = () => {
        const {props} = this.comp;
        const {search} = props;
        search.openAdvSearch(COMMON.searchId, true);
    };

    htmlPrint = () => {
        const {props} = this.comp;
        const {transfer} = props;
        const el = document.querySelector('.table-info').cloneNode(true);
        const table = el.querySelector('.u-table-content');
        table.removeChild(table.lastElementChild);
        const tHeader = el.querySelector('.u-table-header');
        const tr = tHeader.querySelector('tr');
        tr.removeChild(tr.firstElementChild);
        tr.removeChild(tr.firstElementChild);
        const tableTmp = deepCopy(props.meta.getMeta()[COMMON.tableId]);
        let data = deepCopy(props.editTable.getAllRows(COMMON.tableId));
        changeData(data, transfer);
        do_print(
            el,
            {
                title: transfer.language['gx6008-000096'] /* 国际化处理： 调配申请*/,
                maker: transfer.language['gx6008-000094'] /* 国际化处理： 打印人*/,
                date: transfer.language['gx6008-000095'] /* 国际化处理： 打印日期*/,
                maxColLen: getTableTmp(tableTmp).length, // 可以显示的长度
                beforeAppend: (tableDataList) => {
                    tableDataList[0][0] = getTableTmp(tableTmp);
                    return [tableDataList[0]]
                }
            },
            {
                tableTmp: tableTmp,
                data: data
            }
        );
    };

    templatePrint = () => {
        const {props: {transfer}} = this.comp;
        let billids = [transfer.billid];
        print(
            'pdf',
            COMMON.printUrl + '',
            {
                funcode: COMMON.appConfig.appcode,
                nodekey: COMMON.appConfig.appcode,
                oids: billids
            }
        );
    };

    htmlOut = () => {
        let {props} = this.comp;
        let {transfer} = props;
        let dataRows = deepCopy(props.editTable.getAllData(COMMON.tableId)).rows;
        let meta = deepCopy(props.meta.getMeta()[COMMON.tableId]);
        // 输出 将是否默认值修改为 汉字
        changeData(dataRows, transfer);
        changeMeta(meta);
        //输出
        Export(document.querySelector('.u-table-scroll'),
            {
                title: transfer.language['gx6008-000096'] /* 国际化处理： 调配申请*/,
                fileName: transfer.language['gx6008-000246'] /* 国际化处理： 调配办理*/,
                maker: transfer.language['gx6008-000094'] /* 国际化处理： 打印人*/,
                date: transfer.language['gx6008-000095'] /* 国际化处理： 打印日期*/,
            }, {
                data: dataRows,
                meta: meta,
                showIndex: false
            });
    };

    templateOut = () => {
        let {props: {transfer}} = this.comp;
        let billids = [transfer.billid];
        // 点击输出按钮
        output({
            url: COMMON.printUrl,
            data: {
                funcode: COMMON.appConfig.appcode,      //功能节点编码，即模板编码
                nodekey: COMMON.appConfig.appcode,      //模板节点标识
                oids: billids,    // 功能节点的数据主键
                outputType: 'output',
                filename: transfer.language['gx6008-000246'] // 输出文件名
            },
            callback: function () {

            }
        });
    }
}
